package com.zb.util;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.zb.entity.Sms;
import com.zb.exception.SMSException;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * @Author WEN
 * @Date 2023/7/10 0010
 **/
@Log4j2
@Component
public class SmsSendUtil {
    @Value("${aliyun.sms.AccessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.sms.AccessKeySecret}")
    private String secret;

    private static SmsSendUtil smsSendUtil;

    @PostConstruct
    public void init() {
        smsSendUtil = this;
        smsSendUtil.accessKeyId = this.accessKeyId;
        smsSendUtil.secret = this.secret;
    }

    /**
     * 发送短信验证码
     * @param phone 接收者手机号
     * @param code 验证码
     * @return
     */
    public static void sendVerifiCode(String phone, String code) throws SMSException {
        smsSendUtil.sendSms(Sms.verifCode(phone, code));
    }


    private static void sendSms(Sms sms) throws SMSException {
        IAcsClient client = new DefaultAcsClient(DefaultProfile.getProfile(sms.getRegionId(), smsSendUtil.accessKeyId, smsSendUtil.secret));
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("AccessKeyId", smsSendUtil.accessKeyId);
        request.putQueryParameter("PhoneNumbers", sms.getPhoneNumbers());
        request.putQueryParameter("SignName", sms.getSignName());
        request.putQueryParameter("TemplateCode", sms.getTemplateCode());
        request.putQueryParameter("TemplateParam", sms.getTemplateParam());
        if (StringUtils.isNotBlank(sms.getSmsUpExtendCode())) {
            request.putQueryParameter("SmsUpExtendCode", sms.getSmsUpExtendCode());
        }
        if (StringUtils.isNotBlank(sms.getOutId())) {
            request.putQueryParameter("OutId", sms.getOutId());
        }

        CommonResponse response = null;
        try {
            response = client.getCommonResponse(request);
        } catch (ClientException e) {
            throw new SMSException("短信发送失败：" + e);
        }
        System.out.println("=============>>>>>" + response);
        Map map = (Map) JSON.parse(response.getData());
        System.out.println(map);
    }
}
